/**
 * Created by Administrator on 2018/5/27 0027.
 */
import {AsyncStorage} from 'react-native';
import GitHubTrending from 'GitHubTrending';
// 标识区分是最热模块或者是趋势模块
export var FLAG_STORAGE = {flag_popular: 'popular', flag_trending: 'trending'};
export default class DataRepository {
	constructor(flag) {
		this.flag = flag;
		if(flag === FLAG_STORAGE.flag_trending) {
			this.trending = new GitHubTrending();
		}
	}
    saveRepository(url, result, callback){
        if(!url || !result){
            return;
        }
        let wrapData = {
            items:result,
            update_data: new Date().getTime()
        };
        AsyncStorage.setItem(url, JSON.stringify(wrapData),callback);
    }

	fetchRepository(url){
		return new Promise((resolve, reject)=>{
			// 获取本地的数据
			this.fetchLocalRepository(url)
				.then(result=>{
					if(result) {
						resolve(result);
					} else {
						this.fetchNetRepository(url)
							.then(result=>{
								resolve(result);0
							})
							.catch(e=>{
								reject(e);
							})
					}
				})
				.catch(e=>{
                    this.fetchNetRepository(url)
                        .then(result=>{
                            resolve(result);
                        })
                        .catch(e=>{
                            reject(e);
                        })
				})
		})
	}
	fetchLocalRepository(url){
		return new Promise((resolve, reject)=>{
			AsyncStorage.getItem(url,(error, result)=>{
				if(!error) {
					try {
                        resolve(JSON.parse(result));
					}catch (e) {
						reject(e);
					}
				} else {
					reject(error);
				}
			})
		})
	}
	fetchNetRepository(url){
		return new Promise((resolve, reject)=>{
			if(this.flag === FLAG_STORAGE.flag_trending) {
				this.trending.fetchTrending(url)
					.then(result=>{
						if(!result) {
							reject(new Error('responseData is null'));
							return;
						}
						this.saveRepository(url, result);
						resolve(result);
					})
			} else {
                fetch(url)
                    .then(response=>response.json())
                    .then(result=>{
                        if(!result) {
                            reject(new Error('responseData is null'));
                            return;
                        }
                        resolve(result.items);
                        this.saveRepository(url, result.items)
                    })
                    .catch(error=>{
                        reject(error);
                    })
			}

		})
	}

    /**
	 * 判断数据是否过时
     * @param longTime 数据的时间戳
     * @returns {boolean}
     */
	checkData(longTime){
		let cDate = new Date();
		let tDate = new Date();
        tDate.setTime(longTime);
        if(cDate.getMonth() !== tDate.getMonth()) return false;
        if(cDate.getDay() !== tDate.getDay()) return false;
        // if(cDate.getHours() - tDate.getHours() >= 1) return false;
        if(cDate.getHours() - tDate.getHours() !== 0) {
            if((cDate.getHours() - tDate.getHours())*60 + cDate.getMinutes() - tDate.getMinutes() > 1) return false;
		} else {
            if(cDate.getMinutes() - tDate.getMinutes() > 1) return false;
		}
      	return true;
	}
}